package com.igeek.ch02.controller;

import com.igeek.ch02.common.CommonResult;
import com.igeek.ch02.entity.User;
import com.igeek.ch02.service.UserService;
import com.igeek.ch02.utils.JSONUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


@WebServlet(name = "UserUpdateServlet",urlPatterns = "/userUpdate")
public class UserUpdateServlet extends HttpServlet {
    UserService userService=new UserService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        //1.接收请求
        //接收普通域请求参数
        String id1 = request.getParameter("id");
        int id = Integer.parseInt(id1);
        String name = request.getParameter("name");
        String gender = request.getParameter("gender");
        String birthdayStr = request.getParameter("birthday");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date birthday = null;
        try {
            birthday = sdf.parse(birthdayStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //封装User对象
        User user = new User(id , name , gender , birthday);

        //接收上传图片信息
        Part part = request.getPart("pic");
        if(part!=null){
            String oldName = part.getHeader("content-disposition");
            if(oldName!=null && oldName.indexOf(".")>0){
                String newName = UUID.randomUUID()+oldName.substring(oldName.lastIndexOf(".") , oldName.length()-1);
                //给用户设置头像
                user.setPic("/pic/"+newName);
                //给图片服务器路径写出图片信息
                part.write("F:\\115\\temp\\"+newName);
            }else{
                //若没有上传图片，则获取原来的头像，若不为空则需要设置保留原头像
                String pic = userService.viewOne(id).getPic();
                if(pic!=null && !pic.equals("")){
                    user.setPic(pic);
                }
            }
        }

        //2.更新用户的业务
        CommonResult commonResult = null;
        if(user!=null){
            boolean flag = userService.update(user);
            if(flag){
                commonResult = new CommonResult(200 , "更新成功" , flag);
            }else{
                commonResult = new CommonResult(488 , "更新失败");
            }
        }

        //3.响应json数据
        JSONUtils.writeJson(response , commonResult);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        this.doPost(request, response);
    }
}
